/**
 * Created by LiuJie on 2016/10/18.
 * bootstrap dialog 插件
 *
 */
;(function ($, window, undefined) {
    /**
     * dialog插件对象
     * @returns {{init: init}}
     * @constructor
     */
    var DataDialogExt = function () {
        var $element;//$(selector)自己
        var _set;//dialog设置
        var $modal;
        var modal_setting = {
            keyboard:false,//模态框按键盘键ESC是否退出
            show:false,//模态框加载完成后是否立即展示出来
            remote:''//加载远程数据url
        };
        var modal_html_template = '<div class="modal fade data-dialog-ext" tabindex="-1"   role="dialog" aria-hidden="true">'
            + '</div>';
        var main_html_template = '<div class="modal-dialog dialog-box-ext">'
            + '<div class="modal-content">'
            + '<div class="modal-header dialog-box-ext-head">'
            + '<button type="button" class="close head-btn-close" data-dismiss="modal" aria-hidden="true"></button>'
            + '<h4 class="modal-title dialog-box-ext-title"></h4>'
            + '</div>'
            + '<div class="modal-body dialog-box-ext-body">'
            + '</div>'
            + '</div>'
            + '</div>';
        var foot_html_template = '<div class="modal-footer dialog-box-ext-foot">'
            + '<button type="button" class="btn btn-default btn-box-base dialog-box-ext-foot-btn foot-btn-close" data-dismiss="modal">取 消</button>'
            + '<button type="button" class="btn green dialog-box-ext-foot-btn foot-btn-sure">确 定</button>'
            + '</div>';

        /**
         * 初始化dialog函数
         * @param $elem //页面div 本身
         * @param setting//dialog相关设置
         */
        function initDialog($elem, setting) {
            $element = $elem;
            _set = setting;
            modal_setting.keyboard = setting.keyboard;
            modal_setting.show = setting.show;
            var _content = getDialogContent();
            initDialogDom();
            if (!setting.href) {
                initDialogContent(_content);
            } else {
                var _href = setting.href;
                //modal_setting.remote = setting.href;
                if (!(typeof _href === "boolean")) {
                    loadDialogByHref(setting.href);
                }
            }
            $modal = $element.find("div.data-dialog-ext");
            $modal.modal(modal_setting);
            initDialogEvent();
        }
        /**
         * 加载dialog html
         */
        function initDialogDom() {
            if (!$element.find("div.data-dialog-ext").length && !$element.find("div.dialog-box-ext").length) {
                if(_set.modal){
                    $element.append(modal_html_template);
                    $element.find("div.data-dialog-ext").append(main_html_template);
                }else{
                    $element.append(main_html_template);
                }
                if(_set.isSpecialStyle){
                    $element.addClass("special-dialog-layout")
                }
                var $dialogBoxExt = $element.find("div.dialog-box-ext");
                if(_set.showButton){
                    $dialogBoxExt.find("div.modal-content").append(foot_html_template);
                }
                if(_set.width){
                    $dialogBoxExt.css({"width":_set.width+"px"});
                    $dialogBoxExt.find("div.dialog-box-ext-body").css({"width":_set.width+"px"});
                }
                if(_set.maxWidth){
                    $dialogBoxExt.css({"maxWidth":_set.maxWidth+"px"});
                    $dialogBoxExt.find("div.dialog-box-ext-body").css({"maxWidth":_set.maxWidth+"px"});
                }
                if(_set.minWidth){
                    $dialogBoxExt.css({"minWidth":_set.minWidth+"px"});
                    $dialogBoxExt.find("div.dialog-box-ext-body").css({"minWidth":_set.minWidth+"px"});
                }
                if(_set.height){
                    $dialogBoxExt.find("div.dialog-box-ext-body").css({"height":_set.height+"px"});
                }
                if(_set.maxHeight){
                    $dialogBoxExt.find("div.dialog-box-ext-body").css({"maxHeight":_set.maxHeight+"px"});
                }
                if(_set.minHeight){
                    $dialogBoxExt.find("div.dialog-box-ext-body").css({"minHeight":_set.minHeight+"px"});
                }
                if(_set.scrollY){
                    $dialogBoxExt.find("div.dialog-box-ext-body").css({"overflow-y":"auto"});
                }
                if(_set.scrollX){
                    $dialogBoxExt.find("div.dialog-box-ext-body").css({"overflow-x":"auto"});
                }
                if(_set.okText){
                    $dialogBoxExt.find("div.modal-content").find("div.dialog-box-ext-foot").find(".foot-btn-sure").text(_set.okText);
                }
                if(_set.cancelText){
                    $dialogBoxExt.find("div.modal-content").find("div.dialog-box-ext-foot").find(".foot-btn-close").text(_set.cancelText);
                }
                $dialogBoxExt.find("div.modal-content")
                    .find(".dialog-box-ext-title").text(_set.title);
                // initDialogEvent();
            }
        }

        /**
         * 加载远程服务器数据(格式：html)
         */
        function loadDialogByHref(url) {
            var load_url = url;
            $.commonAjax.request(load_url, null, function (result) {
                initDialogContent(result);
            }, "html");
        }
        /**
         * 加载dialog body中的内容
         * @param content type:html
         */
        function initDialogContent(content) {
            var dialog_content = content;
            var $dialog_body = $element.find("div.data-dialog-ext").find("div.dialog-box-ext-body");
            $dialog_body.html(dialog_content);
        }

        /**
         * 初始化dialog插件事件
         */
        function initDialogEvent() {
            //模态框显示之后立即调用此函数
            $modal.on("show.bs.modal",function () {
                try {
                    if(_set.onShow){
                        if($.isFunction(_set.onShow)){
                          _set.onShow();
                        }else{
                            throw new Error("onShow不是一个函数！");
                        }
                    }
                }catch (e){
                    throw new Error(e);
                }

            });
            //模态框显示完成（包括css动画结束）后，触发此函数
            $modal.on("shown.bs.modal",function () {
                try {
                    if(_set.onShowAfter){
                        if($.isFunction(_set.onShowAfter)){
                            _set.onShowAfter();
                        }else{
                            throw new Error("onShowAfter不是一个函数！");
                        }
                    }
                }catch (e){
                    throw new Error(e);
                }
            });
            //模态框关闭时触发的函数
            $modal.on("hide.bs.modal",function () {
                try {
                    if(_set.onClose){
                        if($.isFunction(_set.onClose)){
                            _set.onClose();
                        }else{
                            throw new Error("onClose不是一个函数！");
                        }
                    }
                }catch (e){
                    throw new Error(e);
                }
            });
            //模态框关闭完成（包括css动画已经完成）后触发此函数
            $modal.on("hidden.bs.modal",function () {
                try {
                    resetDialog($modal);
                    $modal.find("form").find("input,select,textarea").val("");
                    if(_set.onCloseAfter){
                        if($.isFunction(_set.onCloseAfter)){
                            _set.onCloseAfter();
                        }else{
                            throw new Error("onCloseAfter不是一个函数！");
                        }
                    }
                }catch (e){
                    throw new Error(e);
                }
            });
            //加载远程服务器数据完成时，触发函数
            $modal.on("loaded.bs.modal",function () {
                try {
                    if(_set.onLoad){
                        if($.isFunction(_set.onLoad)){
                            var result = _set.onLoad();
                            if(result == false){
                                return;
                            }
                        }else{
                            throw new Error("onLoad不是一个函数！");
                        }
                    }
                }catch (e){
                    throw new Error(e);
                }
            });
            var $footer = $element.find("div.dialog-box-ext").find("div.dialog-box-ext-foot");
            $footer.find(".foot-btn-sure").bind("click dbClick",function () {
                try {
                    if(_set.onBeforeSure){
                        if($.isFunction(_set.onBeforeSure)){
                            var result = _set.onBeforeSure();
                            if(result == false){
                                return;
                            }
                        }else{
                            throw new Error("onBeforeSure不是一个函数！");
                        }
                    }
                    if(_set.onSure){
                        if($.isFunction(_set.onSure)){
                             _set.onSure();
                        }else{
                            throw new Error("onSure不是一个函数！");
                        }
                    }
                }catch (e){
                    $.ErrorUtils.throwE(e);
                }
            });
        }

        /**
         * dialog 打开事件
         */
        function dialogShow() {
            $element.css({"display":'block'});
            $element.find("div.data-dialog-ext").modal("show");
        }

        /**
         * dialog关闭事件
         */
        function dialogClose() {
            $element.css({"display":'none'});
            $element.find("div.data-dialog-ext").modal("hide");
        }

        function resetDialog($dialog){
            var $validDiv = $dialog.find("div.input-validate-box");
            var $msg_i = $validDiv.find("i");
            var $msg_span = $validDiv.find("span.valid-message");
            if($validDiv.hasClass("has-success")){
                $validDiv.removeClass("has-success");
            }
            if($validDiv.hasClass("has-error")){
                $validDiv.removeClass("has-error");
            }
            if($msg_i && $msg_i.length){
                $msg_i.remove();
            }
            if($msg_span && $msg_span.length){
                $msg_span.remove();
            }
        }
        
        /**
         *
         * @returns {XMLList|*}
         */
        function getDialogContent() {
            return $element.children();
        }

        return {
            init: function ($elem, setting) {
                initDialog($elem, setting);
            },
            open:function ($elem, p) {
                if($.isPlainObject(p)){
                    if(p.title){
                        $elem.find("h4.dialog-box-ext-title").text(p.title);
                    }
                    if(p.href){
                        $.commonAjax.request(p.href, null, function (result) {
                            $element = $elem;
                            $($element.find("div.data-dialog-ext").find("div.dialog-box-ext-body")).children().remove();
                            initDialogContent(result);
                        }, "html");
                    }
                }
                $elem.css({"display":'block'});
                $elem.find("div.data-dialog-ext").modal("show");
            },
            close: function ($elem, p) {
                if (typeof p === "boolean") {
                    if (p === true) {
                        $elem.css({"display": 'none'});
                        $elem.find("div.data-dialog-ext").modal("hide");
                    }
                } else {
                    resetDialog($elem);
                    $elem.find("form").find("input,select,textarea").val("");
                    $elem.css({"display": 'none'});
                    $elem.find("div.data-dialog-ext").modal("hide");
                }

            },
            load: function ($elem, ob) {
                var _url = ob;
                var queryParams = null;
                var loadFn = ob.loadSuccess;
                if ($.isPlainObject(ob)) {
                    _url = ob.url;
                    if(ob.queryParams){
                        queryParams = ob.queryParams;
                    }
                }
                if (!_url) {
                    console.log("---url为空---");
                    return false
                }
                var $dialog_body = $elem.find("div.data-dialog-ext").find("div.dialog-box-ext-body");
                $dialog_body.html("");
                $.commonAjax.request(_url, queryParams, function (result) {
                    var dialog_content = result;
                    $dialog_body.html(dialog_content);
                    if (loadFn && $.isFunction(loadFn)) {
                        loadFn();
                    }
                }, "html");
            }
        }
    };
    /**
     * dialog插件对外调用接口
     * @param options
     */
    $.fn.DialogExt = function (options,param) {
        var $element = (this instanceof jQuery) ? this : $(this);
        if ($.isPlainObject(options)) {
            var setting = $.extend({}, $.fn.DialogExt.defaults, options);
            DataDialogExt().init($element, setting);
        }
        if (typeof options == "string") {
            var result = DataDialogExt()["" + options + ""]($element, param);
            if (result) {
                return result;
            }
        }
    };
    //dialog插件默认参数
    $.fn.DialogExt.defaults = {
        "width": "",//dialog宽度
        "height": "",//dialog高度
        "maxHeight":"",//dialog最大高度
        "minHeight":"",//dialog最小高度
        "scrollY":false,//是否开启纵向滚动条
        "scrollX":false,//是否开启横向滚动条
        "title": "New Dialog",//dialog标题
        "okText":"",
        "cancelText":"",
        "showButton":true,
        "href": "",
        "modal": true,//是否模态,默认true
        "keyboard":true,//模态框按键盘键ESC是否退出
        "show":false,//模态框加载完成后是否立即展示出来
        "onSure": null,
        "onClose": null,
        "onLoad": null,
        "onBeforeSure": null,
        "onCloseAfter": null,
        "onShow":null,
        "onShowAfter":null,
        "isSpecialStyle":false//是否在屏幕宽度大于768px时设置最大宽度为768px，慎用，
    };
})(jQuery, window, undefined);